/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package com.eric.server.monitor;

import com.eric.server.logic.DefaultLogic;
import com.eric.server.logic.ILogic;
import com.eric.server.logic.packet.ChatToGroupPacket;
import com.eric.server.logic.packet.UserRegisterPacket;
import com.eric.server.packet.Packet;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Sharable
public class MonitorHandler extends ChannelInboundHandlerAdapter {

    public MonitorHandler(){
    }

    ILogic logic = DefaultLogic.me();

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        super.channelUnregistered(ctx);
        logic.leave(ctx.channel());
        System.out.println("连接断开....");
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        System.out.println("建立连接....");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Packet packet = (Packet)msg;
        switch (packet.getPacketType()){
            case UserRegister:
                UserRegisterPacket p = (UserRegisterPacket)packet;
                logic.join(ctx.channel(),p.user,p.room);
                break;
            case ChatToGroup:
                ChatToGroupPacket chatToGroupPacket = (ChatToGroupPacket)packet;
                logic.sendMsg(ctx.channel(),chatToGroupPacket.msg);
                break;
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // Close the connection when an exception is raised.
        cause.printStackTrace();
        ctx.close();
    }

}
